var express = require('express');
var router = express.Router();
var formidbale = require("formidable");
var path = require("path");
var fs = require('fs');
var {root} = require("../config");

/* GET home page. */
router.get('/favicon.ico', function(req, res, next){
  res.end();
});
router.get('/', function(req, res, next) {
  res.redirect("index.html")
});
router.post('/validFileProgress', function(req, res, next) {
  const { fileMd5, name} = req.body;
  const extname = path.extname(name);
  fs.stat(`${root}/upload/${req.body.fileMd5+extname}`,(err,stats)=>{
    if(err) {
      res.json({file:null})
    } else {
      const {size,mtime,ctime} = stats;
      res.json({file:{size,mtime,ctime}});
    }
    
  })
});
router.post('/upload', function(req, res, next) {
  const form = new formidbale.IncomingForm();
  form.uploadDir = `${root}/temp`;
  form.parse(req,(err,fields,files)=>{
    if(err) {
      console.error(err);
      res.json({
        ok:false,
        msg:err,
      })
    } else {
      console.log("----",fields);
      /**
       * chunkLength
       * index
       * fileMd5
       * name
       * totalSize
       */
      const extname = path.extname(fields.name);
      const filePath = `${root}/upload/${fields.fileMd5}${extname}`;
      fs.stat(filePath,(err,stats)=>{
        //文件存在且上传完毕（大小一致）
        if(stats&&stats.size>=fields.totalSize){
          res.json({
            ok:ok
          });
          return;
        }
        //未上传完怎追加文件
        fs.readFile(files.chunk.path,(err,data)=>{
          fs.appendFile(filePath,data,err=>{
            if(err) {
              res.json({
                ok:false,
                msg:err
              })
            } else {//删除temp数据
              fs.unlink(files.chunk.path,err=>{
                if(err) {
                  console.log(`${files.chunk.path}删除失败`);
                }
                //log
              });
              res.json({
                ok:true
              })
            }
          })
        });
      })
    }
  })
});

module.exports = router;
